<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('Controller', 'Controller');
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
App::uses ( 'CakeEmail', 'Network/Email' );

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	//public $components = array('DebugKit.Toolbar'
    //, 'Session',
     //       'Auth' => array(
      //              'loginRedirect' => array('controller' => 'customers', 'action' => 'view'),
      //              'logoutRedirect' => array('controller' => 'pages', 'action' => 'display')
        //   )
            
            /*, 'Auth' => array(
        'loginRedirect' => array('controller' => 'Pltcustomers', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'Pages', 'action' => 'display','aboutus'),
        'authorize' => array('Controller')
    ));



    public $helper = array('Html', 'Form'/*, 'Session');

    /*public function beforeFilter() {
        $this->Auth->allow('display', 'index', 'view', 'edit',  'add', 'delete', 'signout', 'signin', 'register');
    }*/
    /*public function beforeFilter() {
        parent::beforeFilter();

        $this->Auth->allow('display');
        $this->Auth->loginRedirect = array('controller' => 'PltcustomersController', 'action' => 'index');
        $this->Auth->logoutRedirect = array('controller' => 'pages', 'action' => 'display', 'aboutus');
    }*/

    /*public function isAuthorized($pltcustomer) {
        if (isset($pltcustomer['is_admin']) && $pltcustomer['is_admin'] == '1') {
            return true;
        }

        return false;
    }*/
    
    /*public function beforeFilter() {
        parent::beforeFilter();
            $this->Auth->allow('display', 'signin');
    }*/
    
    
    //----------------------  ---------------------
    
    public $components = array(
       //'DebugKit.Toolbar',
        'Session', 
        'Auth' => array(
            'authenticate' => array(
                'Form' => array(
                    'userModel' => 'Customer',
                    'fields' => array(
                        'username' => 'username',
                        'password' => 'password',
                    ),
                    'scope' => array(
                        'status_id' => '2',
                    ),
                ),
            ),
            'loginAction' => array('controller' => 'customers', 'action' => 'login'),
            'loginRedirect' => array('controller' => 'customers', 'action' => 'index'/*, $this->Auth->user('id')*/),
            'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'pagehome'),
            'authError' => 'Error',
            'authorize' => array('Controller')
        )
    );
    
    public $helpers = array('Html', 'Form', 'Session', 'Paginator', 'Js' =>array('prototype', 'scriptaculous', 'Jquery'));
    
    //determine what logged in user has access to
    public function isAuthorized($customer) {
        return true;
    }

    public function getLoggedUserId() {
        return $this->Session->read('Auth.User.id');
    }
    public function userLogged() {
        return $this->Session->check('Auth.User');
    }

    //determine what non - logged in user has access to
    public function beforeFilter() {
        $this->Auth->allow('display', 'activate', 'captcha');
        
        //pass variable to default.ctp
        $this->set('logged_in', $this->Auth->loggedIn());
        $this->set('current_customer', $this->Auth->user());
        
        $roles = $this->Auth->user('group_id');
        $webroot = $this->request->webroot;
        $this->set("webroot",$webroot);
        if ($roles == '1') {
            $this->set('is_admin', true);
        } else {
            $this->set('is_admin', false);
        }
    }

    public $pageTitle;

    public function beforeRender() {
        $this->set('title_for_layout', $this->pageTitle);
    }
    
    //----------------------- Items and Photos related functions ---------------
    
    public function uploadFiles($folder, $formdata, $itemId = null) {
        
        $folder_url = WWW_ROOT.$folder;
        $rel_url = $folder;
        
        if(!is_dir($folder_url)) {
            mkdir($folder_url);
        }
        
        if ($itemId) {
            $folder_url = WWW_ROOT.$folder.'/'.$itemId;
            $rel_url = $folder.'/'.$itemId;
            
            if (!is_dir($folder_url)) {
                mkdir($folder_url);
            }
        }
        
        $permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png');
        
        $filename = str_replace('', '_', $formdata['name']);
        
        $typeOK = false;
        
        foreach ($permitted as $type) {
            if ($type == $formdata['type']) {
                $typeOK = true;
                break;
            }
        }
        
        if ($typeOK) {
            switch ($formdata['error']) {
                case 0:
                    $full_url = $folder_url.'/'.$formdata['name'];
                    $url =  $rel_url.'/'.$formdata['name'];
                    
                    $success = move_uploaded_file($formdata['tmp_name'], $url);
                    
                    if ($success) {
                        $result['urls'][] = $formdata['name'];
                    } else {
                        $result['errors'][] = "Error uploaded ".$formdata['name'].". Please try again";
                        break;
                    }
                case 3:
                    $result['errors'][] = "Error uploading ".$formdata['name'].". Please try again";
                    break;
                
                default:
                    $result['errors'][] = "System error uploading".$formdata['name'].". Please contact webmaster";
                    break;
            }
        } elseif ($formdata['error'] == 4) {
            $result['nofiles'][] = "No files selected";
        } else {
            $result['errors'][] = $formdata['name']."cannot be uploaded. Acceptable file types are gif, jpg, png";
        }
        
        return $result;
    }
    /**
     * Send email
     */
    public function sendEmail($email = "", $subject = "", $message = "") {
    	try {
    		$cakeEmail = new CakeEmail ( "smtp" );
    		$cakeEmail->to ( $email );
    		$cakeEmail->subject ( $subject );
    		$content = $cakeEmail->send ( $message );
    		$this->log ( $email . "-->" . $message, "email" );
    	} catch ( Exception $e ) {
    		$this->log ( "Exception \n" . $e, "email" );
    	}
    }
    /**
     * Send email using the template
     */
    public function sendEmailByTemplate($data = array(), $template = "") {
    	try {
    		$cakeEmail = new CakeEmail ( "smtp" );
    		$cakeEmail->template ( $template );
    		$cakeEmail->to ( $data ["email"] );
    		$cakeEmail->emailFormat ( "html" );
    		$cakeEmail->subject ( $data ["subject"] );
    		$cakeEmail->viewVars ( $data );
    		$cakeEmail->send ();
    		$this->log ( $template . ":" . $data ["email"], "email" );
    	} catch ( Exception $e ) {
    		$this->log ( "Exception \n" . $e, "email" );
    	}
    }
    /**
     * Send error message to my email
     */
    public function sendToMe($msg = "", $subject = "website error") {
    	$email = "philippa410@gmail.com";
    	try {
    		$msg .= "\nAddress:" . env ( 'HTTP_HOST' ) . $this->request->here () . "\nClientIP:" . $this->request->clientIp () . "\nSourceLanguage:" . $this->request->header ( "ACCEPT_LANGUAGE" );
    		$cakeEmail = new CakeEmail ( "smtp" );
    		$cakeEmail->template ( "default" );
    		$cakeEmail->to ( $email );
    		$cakeEmail->emailFormat ( "html" );
    		$cakeEmail->subject ( $subject );
    		$cakeEmail->send ( $msg );
    	} catch ( Exception $e ) {
    		$this->log ( "Exception \n" . $e, "email" );
    	}
    }
}
